package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.Teacher;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.TeacherService;
import cn.edu.sdjzu.xg.eagle.util.Condition;
import cn.edu.sdjzu.xg.eagle.util.ControllerHelper;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import cn.edu.sdjzu.xg.eagle.util.Pagination;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;


/**
 * @author tg.si@188.com
 * @todo
 * @since 2022/10/12 18:56
 */
@WebServlet("/teacherRead.ctl")
public class TeacherReadCtrl extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(TeacherReadCtrl.class);

    /**
     * 条件查询、分页响应
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //授权验证
//        String idInToken = JwtUtil.parseToken(request);
//        log.debug("id in token=" + idInToken);

        //创建JSON对象message_jsonObj，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            message_jsonObj.put("message", "未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            //读取分页信息，如{"pagination":{"pageNo":1,"pageSize":2}}，形成分页对象
            //将JSON字串解析为Pagination对象
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            //分页获得符合条件的教师
            Collection<Teacher> teachers = ServiceFactory.getService
                    (TeacherService.class,"TeacherServiceImpl")
                    .findAll(conditionList, pagination);
            message_jsonObj.put("totalNum", pagination.getTotalNum());
            message_jsonObj.put("records", teachers);
            //响应message_jsonObj到前端
            response.getWriter().println(message_jsonObj);
        } catch (BaseException e) {
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        }
    }
}